<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">{{title}}</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          auto-complete="off"
          placeholder="账号"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <div class="captcha-container">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
          </div>
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login"
import Cookies from "js-cookie"
import { encrypt, decrypt } from '@/utils/jsencrypt'

export default {
  name: "Login",
  data() {
    return {
      title: process.env.VUE_APP_TITLE,
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: true,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          {required: true, trigger: "blur", message: "请输入您的账号"}
        ],
        password: [
          {required: true, trigger: "blur", message: "请输入您的密码"}
        ],
        code: [{required: true, trigger: "change", message: "请输入验证码"}]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: false,
      // 注册开关
      register: true,
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.getCode()
    this.getCookie()
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img
          this.loginForm.uuid = res.uuid
        }
      })
    },
    getCookie() {
      const username = Cookies.get("username")
      const password = Cookies.get("password")
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      }
    },
    // 检查授权是否到期
    checkAuthorization() {
      // 这里实现您的授权检查逻辑
      // 示例：从localStorage或接口获取授权信息
      const authInfo = localStorage.getItem('app_auth_info');
      if (authInfo) {
        try {
          const auth = JSON.parse(authInfo);
          const expireTime = new Date(auth.expireTime).getTime();
          const currentTime = new Date().getTime();

          // 如果授权已过期
          if (currentTime > expireTime) {
            return {authorized: false, message: '授权已过期'};
          }
          return {authorized: true};
        } catch (e) {
          console.error('解析授权信息失败:', e);
          return {authorized: false, message: '授权信息异常'};
        }
      }
      // 如果没有授权信息，默认认为需要授权检查
      return {authorized: false, message: '未找到授权信息'};
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, {expires: 30})
            Cookies.set("password", encrypt(this.loginForm.password), {expires: 30})
            Cookies.set('rememberMe', this.loginForm.rememberMe, {expires: 30})
          } else {
            Cookies.remove("username")
            Cookies.remove("password")
            Cookies.remove('rememberMe')
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            // 登录成功后检查授权
            const authCheck = this.checkAuthorization();
            if (!authCheck.authorized) {
              // 授权检查不通过，跳转到授权页面
              this.$message.warning(authCheck.message || '请先进行授权');
              this.$router.push({path: '/authorization'}).catch(() => {
              });
            } else {
              // 授权正常，正常跳转
              this.$router.push({path: this.redirect || "/"}).catch(() => {
              });
            }
          }).catch(() => {
            this.loading = false
            if (this.captchaEnabled) {
              this.getCode()
            }
          })
        }
      })
    }
  }
}
</script>


<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/yxxt2.jpg");
  background-size: cover;
  padding: 20px;

  @media (max-width: 768px) {
    padding: 10px;
    background-position: center;
  }
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;

  @media (max-width: 768px) {
    font-size: 24px;
    margin-bottom: 25px;
  }
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  z-index: 1;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  @media (max-width: 768px) {
    width: 100%;
    padding: 20px;
    margin-right: 0;
  }

  @media (max-width: 480px) {
    padding: 15px;
  }

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.captcha-container {
  display: flex;
  gap: 10px;

  .el-input {
    flex: 1;
  }

  @media (max-width: 480px) {
    flex-direction: column;

    .login-code {
      width: 100%;
      height: 45px;
      margin-top: 10px;
    }
  }
}

.login-code {
  width: 33%;
  height: 38px;

  @media (max-width: 480px) {
    width: 40%;
  }

  img {
    cursor: pointer;
    vertical-align: middle;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;

  @media (max-width: 480px) {
    height: 45px;
  }
}

// 移动端专用样式
@media (max-width: 768px) {
  .login-form {
    .el-form-item {
      margin-bottom: 20px;
    }

    .el-button {
      height: 45px;
      font-size: 16px;
    }
  }

  .el-checkbox {
    display: block;
    margin-bottom: 20px !important;
  }
}

@media (max-width: 480px) {
  .login-form {
    .el-form-item__content {
      display: flex;
      flex-direction: column;
    }
  }
}
</style>
